/**
 * Copyright (c) 2011 Axa Holding Belgium, SA. All rights reserved.
 * This software is the confidential and proprietary information of the AXA Group.
 */
package chabernac.android.tools;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import chabernac.android.wordbattle.R;

public class Translator {
  private static Translator INSTANCE;

  private final Context myContext;

  private Map<String, String> myCache = new HashMap<String, String>();

  private Translator( Context aActivity ) {
    super();
    myContext = aActivity;
  }

  public static void initialize(Context anActivity){
    if(INSTANCE == null){
      INSTANCE = new Translator( anActivity );
    }
  }

  public static String translate(String aString){
    if(INSTANCE == null) return "Initialize translator first";
    return INSTANCE.translat( aString.replace( ' ', '_' ) );
  }

  private String translat(String aString){
    if(!myCache.containsKey( aString )){
      myCache.put(aString, lookup(aString));
    }
    return myCache.get(aString);
  }
  
  public static int getResource(String aString){
    try {
      Field theField = R.string.class.getField( aString );
      return theField.getInt( R.string.class ) ;
    } catch ( Exception e ) {
      return -1;
    }
  }
  
  private String lookup(String aString){
    try {
      Field theField = R.string.class.getField( aString );
      return myContext.getResources().getString( theField.getInt( R.string.class ) );
    } catch ( Exception e ) {
      return aString;
    }
  }
  
  public static boolean contains(String aString){
    if(INSTANCE == null) return false;
    return INSTANCE.contain( aString.replace( ' ', '_' ) );
  }
  
  private boolean contain(String aString){
    try {
      Field theField = R.string.class.getField( aString );
      myContext.getResources().getString( theField.getInt( R.string.class ) );
      return true;
    } catch ( Exception e ) {
      return false;
    }
  }
  
  public static void clear(){
    if(INSTANCE == null) return;
    INSTANCE.myCache.clear();
  }
}
